<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-row>
        <!--<el-col :span="4.5">
          <el-form-item label="项目编号" prop="projectCode">
            <el-select v-model="queryParams.projectCode" filterable placeholder="请输入或选择项目编号"  style="width: 200px;">
              <el-option
                  v-for="item in projectOptions"
                  :key="item"
                  :label="item"
                  :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>-->
        <!--<el-col :span="4">
          <el-form-item label="项目名" prop="projectName">
            <el-input
              v-model="queryParams.projectName"
              placeholder="请输入项目名"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>-->
        <!--<el-col :span="4">
          <el-form-item label="期数" prop="number">
            <el-input
                v-model="queryParams.number"
                placeholder="请输入期数"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>-->
      </el-row>

      <el-row>
        <el-col :span="4">
          <el-form-item label="创建人" prop="createBy">
            <el-input
                v-model="queryParams.createBy"
                placeholder="请输入创建人"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="创建时间">
            <el-date-picker
                v-model="daterangeCreateTime"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="更新人" prop="updateBy">
            <el-input
                v-model="queryParams.updateBy"
                placeholder="请输入更新人"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="更新时间">
            <el-date-picker
                v-model="daterangeUpdateTime"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:output:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:output:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:output:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:output:export']"
          v-if="false">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="outputList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" prop="id" v-if="false" />
      <el-table-column align="center" prop="areaId" v-if="false" />
      <el-table-column label="项目编号" align="center" prop="projectCode" v-if="false"/>
      <el-table-column label="项目名" align="center" prop="projectName" sortable :sort-method="nameSort"/>
      <el-table-column label="累计含税产值" align="center" prop="outputWithTax" sortable/>
      <el-table-column label="产值税率" align="center" prop="outputTaxRate" sortable>
        <template #default="scope">
          <span>{{ scope.row.outputTaxRate * 100 }}%</span>
        </template>
      </el-table-column>
      <el-table-column label="累计除税产值" align="center" prop="outputNoTax" sortable/>
      <el-table-column label="累计应收账款" align="center" prop="totalReceivable" sortable/>
      <el-table-column label="累计已收账款" align="center" prop="totalReceived" sortable/>
      <el-table-column label="累计应付账款" align="center" prop="totalPayable" sortable/>
      <el-table-column label="累计已付账款" align="center" prop="totalPaid" sortable/>
      <el-table-column label="期数" align="center" prop="dateNumber" sortable/>
      <!--<el-table-column label="备注或附件" align="center" prop="remark" />-->
      <el-table-column label="创建人" align="center" prop="createBy" v-if="false"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" sortable v-if="false">
      </el-table-column>
      <el-table-column label="更新人" align="center" prop="updateBy" v-if="false"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180" sortable v-if="false">
        <!--<template #default="scope">-->
        <!--  <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>-->
        <!--</template>-->
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:output:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:output:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产值对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="outputRef" :model="form" :rules="rules" label-width="80px" style="width: 500px;">

        <div class="centered">
          <el-form-item label="期数选择" prop="dateNumber"  label-width="140px" class="custom-label">
            <el-date-picker type="month"
                            v-model="form.dateNumber"
                            format="YYYY-MM"
                            value-format="YYYY-MM"
                            :style="{width: '100%', fontSize: '18px'}"
                            placeholder="请选择期数"
                            clearable
                            style="width: 200px;">
            </el-date-picker>
          </el-form-item>
        </div>
        <span>&nbsp</span>
        <!--<el-form-item label="累计应收账款" prop="totalReceivable" label-width="140px">
          <el-input v-model="form.totalReceivable" placeholder="请输入累计应收账款" style="width: 340px;" />
        </el-form-item>-->
        <el-form-item label="累计已收账款" prop="totalReceived" label-width="140px">
          <el-input v-model="form.totalReceived" placeholder="请输入累计已收账款" style="width: 340px;" />
        </el-form-item>
        <!--<el-form-item label="累计应付账款" prop="totalPayable" label-width="140px">
          <el-input v-model="form.totalPayable" placeholder="请输入累计应付账款" style="width: 340px;" />
        </el-form-item>-->
        <el-form-item label="累计已付账款" prop="totalPaid" label-width="140px">
          <el-input v-model="form.totalPaid" placeholder="请输入累计已付账款" style="width: 340px;" />
        </el-form-item>

        <!--<el-form-item label="累计含税产值" prop="outputWithTax" label-width="140px">
          <el-input v-model="form.outputWithTax" placeholder="请输入累计含税产值" style="width: 340px;" />
        </el-form-item>
        <el-form-item label="产值税率" prop="outputTaxRate" label-width="140px">
        <el-input v-model="form.outputTaxRate" placeholder="请输入产值税率" style="width: 170px;" />
      </el-form-item>

        <el-form-item label="相关文件" prop="remark" label-width="140px">
          <el-button
              type="info"
              plain
              icon="Upload"
              @click="handleImport"
              v-hasPermi="['system:output:upload']"
          >上传</el-button>
        </el-form-item>-->

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 产值文件导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          :before-upload="beforeUpload"
          :headers="upload.headers"
          :action="upload.url + '?id=' + upload.id"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              只能上传不超过 40MB 的文件
            </div>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="Output">
import { listOutput, getOutput, delOutput, addOutput, updateOutput } from "@/api/system/output";
import { getToken } from "@/utils/auth";

/** 导入按钮操作 */
function handleImport() {
  upload.title = "产值相关文件导入";
  upload.open = true;
  console.log("handleImport ID value:", upload.id);
};
/*** 上传参数 */
const upload = reactive({
  // 是否显示弹出层（明细导入）
  open: false,
  // 弹出层标题（明细导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的明细数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/output/upload",
  // id
  id: null,
});
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit({ id: upload.id });
  console.log("submit ID value:", upload.id);
};

const { proxy } = getCurrentInstance();

const outputList = ref([]);
const projectOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreateTime = ref([]);
const daterangeUpdateTime = ref([]);
const dateNumber = ref(getCurrentYearMonth());

// 获取当前 URL 中的查询参数部分
const queryString = window.location.search;
// 使用 URLSearchParams 对象解析查询参数
const urlParams = new URLSearchParams(queryString);

const nameSort = (a, b) => {
  return a.projectName.localeCompare(b.projectName,'zh');
};

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectCode: null,
    projectName: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    areaId: urlParams.get('areaId'),
    // dateNumber: ref(getCurrentYearMonth()),
  },
  rules: {
    dateNumber: [{
      required: true,
      message: '请选择期数',
      trigger: 'change'
    }],
  },
});

const { queryParams, form, rules } = toRefs(data);


function beforeUpload(file) {
  let isRightSize = file.size / 1024 / 1024 < 40;
  if (!isRightSize) {
    proxy.$message.error('文件大小超过 40MB');
  }
  return isRightSize;
}

/** 查询产值列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  queryParams.value.params["areaId"] = queryParams.value.areaId;
  console.log("areaId: " + queryParams.value.areaId);
  if (null != daterangeCreateTime && '' !== daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  if (null != daterangeUpdateTime && '' !== daterangeUpdateTime) {
    queryParams.value.params["beginUpdateTime"] = daterangeUpdateTime.value[0];
    queryParams.value.params["endUpdateTime"] = daterangeUpdateTime.value[1];
  }
  listOutput(queryParams.value).then(response => {
    outputList.value = response.dataList.rows;
    total.value = response.dataList.total;
    projectOptions.value = response.projectCodeList;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    projectCode: null,
    projectName: null,
    totalReceived: null,
    totalReceivable: null,
    outputNoTax: null,
    outputTaxRate: null,
    outputWithTax: null,
    totalPayable: null,
    totalPaid: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("outputRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  daterangeUpdateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.dateNumber = dateNumber;
  form.value.areaId = queryParams.value.areaId;
  open.value = true;
  title.value = "添加产值";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  upload.id = _id;
  getOutput(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改产值";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["outputRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOutput(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOutput(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除产值编号为"' + _ids + '"的数据项？').then(function() {
    return delOutput(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/output/export', {
    ...queryParams.value
  }, `output_${new Date().getTime()}.xlsx`)
}
// 获取当前年月的函数
function getCurrentYearMonth() {
  const now = new Date();
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 补足月份的两位数
  return `${year}-${month}`;
}
getList();
</script>
<style>
.centered {
  display: flex;
  justify-content: center;
}

.custom-label .el-form-item__label {
  font-size: 18px;
}
</style>